<template>
  <div>
    <el-dialog
      :title="dialogInfo.isAdd ? '添加商品规格' : '编辑商品规格'"
      :visible.sync="dialogInfo.isShow"
      :before-close="cancel"
      center
    >
      <el-form :model="specsInfo" :rules="rules" ref="specsInfo">
        <el-form-item
          label="商品规格名称"
          :label-width="formLabelWidth"
          prop="specsname"
        >
          <el-input v-model="specsInfo.specsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="规格属性"
          :label-width="formLabelWidth"
          v-for="(item, index) in attrArr"
        :key="index">
          <el-input
            class="inp_Info"
            v-model="item.value"
            autocomplete="off"
          ></el-input>
          <el-button v-if="index == 0" @click="add_info" type="primary"
            >新增规格属性</el-button
          >
          <el-button @click="del_info(index)" v-else type="danger"
            >删除</el-button
          >
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="specsInfo.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { specsadd, specsedit, specsinfo } from "../../request/api";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      specsInfo: {
        specsname: "", //商品规格名称
        attrs: "", //规格属性值"白色,红色，黄色"
        status: 1, //状态1正常2禁用
      },
      formLabelWidth: "120px", //label宽度
      //规则验证
      rules: {
        specsname: [
          { required: true, message: "请输入商品规格名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      //定义一个数组 用于循环遍历动态表单项
      attrArr: [
        {
          value: "", //input的双向数据绑定内容
        },
      ],
    };
  },
  props: ["dialogInfo"],
  methods: {
    //封装一个动态添加表单项的事件
    add_info() {
      //对添加的表单项进行一个控制
      if (this.attrArr.length > 4) {
        this.$message.warning("最多添加4项！！！不能再加了。。。");
      } else {
        this.attrArr.push({
          value: "",
        });
      }
    },
    //动态删除表单项
    del_info(n) {
      this.attrArr.splice(n, 1);
    },
    ...mapActions({
      getSpecs: "specs/getSpecsListAction",
      getCount: "specs/getCountAction",
    }),
    //封装一个取消事件
    cancel() {
      //去改变父组件的isShow的状态
      this.$emit("cancel", false);
      //调取清空事件
      this.reset();
    },
    //封装一个清空事件
    reset() {
      this.specsInfo = {
        specsname: "", //商品规格名称
        attrs: "", //规格属性值
        status: 1, //状态1正常2禁用
      };
      //调用清空验证的方法
      this.$refs.specsInfo.resetFields();
      //清空动态表单项
      this.attrArr = [
        {
          value: "",
        },
      ];
    },

    //封装一个查询一条数据的接口
    lookup(id) {
      specsinfo({ id }).then((res) => {
        if (res.code == 200) {
          this.specsInfo = res.list[0];
          this.specsInfo.id = id;
          /* 
           后端返回的数据格式： attrs: ["天空蓝", "深邃灰", "暗夜紫"]
           我们要想实现回显 ，我们界面要求数据格式应该是：
            [{value:"天空蓝"},{value:"深邃灰",},{value:"暗夜紫"}]
          */
          this.specsInfo.attrs.map((item, idx) => {
            console.log(item, "iiiii");
            if (idx == 0) {
              this.attrArr[0].value = item;
            } else {
              this.attrArr.push({
                value: item,
              });
            }
          });
        }
      });
    },
    // 确定事件
    confirm() {
      this.$refs.specsInfo.validate((valid) => {
        if (valid) {
          /* 
              后端要求attrs的数据格式是："1,2,3"
              我们获取的动态表单项的数组是 [{value:1},{value:2},{value:3}]
              总结： [{value:1},{value:2},{value:3}]  =>"1,2,3"
              步骤：
              [{value:1},{value:2},{value:3}] =>[1,2,3]=>"1,2,3"
            */
          this.specsInfo.attrs = this.attrArr
            .map((item) => item.value)
            .join(",");
          if (this.dialogInfo.isAdd) {
            specsadd(this.specsInfo).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                //重新调用接口列表以及总条数
                this.getSpecs();
                this.getCount();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            specsedit(this.specsInfo).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                //重新调用接口列表以及总条数
                this.getSpecs();
                this.getCount();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          this.$message.error("验证失败");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.inp_Info {
  width: 76%;
}
</style>
